/**********************************************************

@description:
*File Name:graph.c
*Author: ydx
*mail: yudongxiang93@163.com
*Create Time: Wed 30 Apr 2025 10:53:12 PM CST
**********************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
//vexs not gothrough, the arc is MAX
//vexs gothrough with itself, the arc is 0
//
#define MAX 32767
typedef struct graph{
	char *vexs;
	int **arcs;
	int vex_num,arc_num;
}graph;
typedef struct edge{
	char vex;//record set U -> the start of the minmum edge
	int weight;
}edge;

edge* init_edge(graph* g,int index){
	edge* edge=(struct edge*)malloc(g->vex_num*sizeof(edge));
	assert(edge);
	for(int i=0;i<g->vex_num;i++){
		edge[i].vex=g->vexs[index];
		edge[i].weight=g->arcs[index][i];
	}
	return edge;
}
int getMinEdge(edge* edge,int vex_num){
	int index;
	int min=MAX;
	for(int i=0;i<vex_num;i++){
		if(edge[i].weight !=0 && min>edge[i].weight){
			min = edge[i].weight;
			index=i;
		}
	}
	return index;
}
void prim(graph* g,int index){
	int min;
	edge* edge=init_edge(g,index);
	for(int i=0;i<g->vex_num-1;i++){
		min=getMinEdge(edge,g->vex_num);
		printf("v%c-->v%c,weight=%d\n",edge[min].vex,g->vexs[min],edge[min].weight);
		edge[min].weight=0;
		for(int j=0;j<g->vex_num;j++){
			if(g->arcs[min][j]<edge[j].weight){
				edge[j].weight=g->arcs[min][j];
				edge[j].vex=g->vexs[min];
			}
		}
	}
}

graph * init_graph(int vex_num){
	graph *g=(graph*)malloc(sizeof(graph));
	g->vexs=(char*)malloc(sizeof(char)*vex_num);
	g->arcs=(int**)malloc(sizeof(int*)*vex_num);
	for(int i=0;i<vex_num;i++){
		g->arcs[i]=(int*)malloc(sizeof(int)*vex_num);
	}
	g->vex_num=vex_num;
	g->arc_num=0;
	return g;
}
void createGraph(graph *g,char *vexs,int* arcs){
	for(int i=0;i<g->vex_num;i++){
		g->vexs[i]=vexs[i];
		for(int j=0;j<g->vex_num;j++){
			g->arcs[i][j]=*(arcs+i*g->vex_num+j);
			if(g->arcs[i][j] != 0 && g->arcs[i][j] != MAX){
				g->arc_num++;
			}
		}
	}
	g->arc_num/=2;
}
void dfs(graph *g,int* visited,int index){
	printf("%c\t",g->vexs[index]);
	visited[index]=1;
	for(int i=0;i<g->vex_num;i++){
		if(g->arcs[index][i]>0 && g->arcs[index][i] != MAX && !visited[i]){
			dfs(g,visited,i);
		}
	}
}
int main(){
	graph* g=init_graph(6);
	int arcs[36]={
		0,6,1,5,MAX,MAX,
		6,0,5,MAX,3,MAX,
		1,5,0,5,6,4,
		5,MAX,5,0,MAX,2,
		MAX,3,6,MAX,0,6,
		MAX,MAX,4,2,6,0,
	};
	createGraph(g,"123456",arcs);

	printf("dfs:");
	int *visited=(int*)malloc(sizeof(int)*g->vex_num);
	memset(visited,0,g->vex_num*sizeof(int));
	dfs(g,visited,0);
	printf("\n");
	prim(g,0);
	printf("\n");
	
}
